# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.2manhua.com/comic/\d+/ 解析器
#
#*******************************************************************************
from base import *

tag='2manhua'

#---------------------------- 验证模块 ----------------------------

def url_judgement(url):
    if re.match(r'http://www.2manhua.com/comic/\d+/',url):
        return valid_check(url)
    return False

def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        content=content.decode('utf-8')
        if re.search("页面不存在",content):
            return False
        return get_loader(url)
    return False

def get_loader(url):
    return TwomanhuaLoader(url,TwomanhuaPageParser,TwomanhuaVolParser)

#---------------------------- 下载器 ----------------------------

class TwomanhuaLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class TwomanhuaPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)

    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>').findall(content)[0]
        # description
        self.comic.description=re.compile(r'<div id="intro-all" class="none"><p style="text-indent:2em;">(.*?)<br>',re.S|re.M).findall(content)[0].strip()
        # cover
        self.comic.cover=re.compile(r'<p class="hcover"><img(.*?)src="(.*?)"').findall(content)[0][1]
        # vols
        vols_content=re.compile(r'<div class="chapter-list cf mt10" id="chpater-list-1">(.*?)</div>',re.S|re.M).findall(content)[0]
        self.feed(vols_content)
    
    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.comic.vols.append(InfoVol('http://www.2manhua.com'+infos['href'],infos['title'].strip()))

class TwomanhuaVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    def work(self,content):
        js_content=re.compile(r'\}\(\'(.*?).split',re.S|re.M).findall(content)[0]
        encs=re.compile(r'\[(.*?)\]',re.S|re.M).findall(js_content)[0].replace('\\','').replace('"','')
        vals=js_content.split(',')
        a,c,key_arr,dec_arr=int(vals[-3]),int(vals[-2])-1,vals[-1].replace("'",'').split('|'),{}
        while c>=0:
            idx=e_func(c,a)
            dec_arr[idx]=key_arr[c] or idx
            c-=1
        def rep(m):
            enc=m.group()
            dec=None
            try:
                dec=dec_arr[enc]
            except:
                dec=enc
            return dec
        pic_index=1
        for url in encs.split(','):
            url=re.subn(r'\w+',rep,url)[0]
            url=url.replace("'",'')
            self.pic_urls.append(('http://tupian.333dm.com'+url,zero_prefix(pic_index)))
            pic_index+=1
def to36(val):
    return toRadix(val,36)

def e_func(c,a):
    c,a=int(c),int(a)
    res=None
    if c<a: 
        res=''
    else:   
        res=e_func(int(c/a),a)
    c=c%a
    if c>35: 
        res+=chr(c+29)
    else: 
        res+=to36(c)
    return res